package com.ep.thirdPlatformProject.job.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.fastjson.JSON;

import com.ep.thirdPlatformProject.job.model.lbs.LBSCityModel;
import com.ep.thirdPlatformProject.job.model.lbs.LBSCityResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api")
@Tag(name = "表格导出测试相关文档")
public class ExcelController  {
    @GetMapping("/hello")
    public String hello() {

        return "Hello World!";
    }


    @GetMapping(value = "/exportAllCityList", produces  = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    @Operation(summary  = "导出全国所有的城市")
    @Parameters({
            @Parameter(name = "fileName", description = "文件名",  required = true, in = ParameterIn.QUERY),
    })
    public void exportAllCityList(HttpServletResponse response2, @RequestParam("fileName")String excelFilePath) throws IOException {
        // 填写API地址和请求参数
        String apiUrl = "https://restapi.amap.com/v3/config/district?subdistrict=2&key=aae7a42b932e7b29807e07d2718a3a88";

        // 发送HTTP请求并获取响应数据
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(apiUrl)
                .build();

        List<LBSCityModel> res = new ArrayList<>();
        Response response = client.newCall(request).execute();
        assert response.body() != null;
        String responseBody = response.body().string();
        LBSCityResult result = JSON.parseObject(responseBody, LBSCityResult.class);

        // 解析API响应数据
        List<LBSCityModel> cityDataList = result.getDistricts();

        LBSCityModel country = cityDataList.get(0);

        String name = country.getName();

        for (LBSCityModel province : country.getDistricts()) {
            String provinceName = province.getName();
            List<LBSCityModel> cityModelList = province.getDistricts();

            for (LBSCityModel city : cityModelList) {
                city.setCountry(name);
                city.setProvince(provinceName);
                String center = city.getCenter();
                String[] split = center.split(",");
                city.setLatitude(split[0]);
                city.setLongitude(split[1]);
                res.add(city);
            }
        }
        // 关闭响应体
        response.body().close();
        // 将城市数据导出为Excel文件

        // 设置导出文件名和响应头
        response2.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        response2.setHeader("Content-Disposition", "attachment; filename*=" + URLEncoder.encode(excelFilePath, StandardCharsets.UTF_8)+".xlsx");        // 将数据导出为Excel文件
        ExcelWriterBuilder writerBuilder = EasyExcel.write(response2.getOutputStream(), LBSCityModel.class);
        writerBuilder.sheet().doWrite(res);

    }
}
